折叠菜单 & 选项卡jQuery(4-4)

item

折叠菜单

  • [x] 思路
  • [ ] 找到标签绑定点击事件,所有标签内容都隐藏,点击谁,就出现,其他周边元素的内容收起来
    1
    2
    3
    4
    $('.menu').find('h2').on('click',function(){
    //console.log(this); //原生的dom对象
    $(this).next().slideToggle(300).parent().siblings().children('ul').slideUp(300);
    });

选项卡

  • [x] 思路
  • [ ] 对于标签绑定点击事件:

    • 点击谁,就给谁添加变颜色的class=”bg”属性
    • 同时去除其他元素已添加过的class=”bg”属性
      1
      $(this).addClass('bg').siblings().removeClass('bg').end();
  • [ ] 对于标签内容

    • 找到对应标签的内容元素
      • 遍历这些元素当index与点击的index相等时(或者eq(index)直接找到对应元素)
        1
        2
        3
        4
        5
        $(this).parent().nextAll('div').eq($index)
        $(this).parent().nextAll().each(function(index, item) {
        index === $index?
        })
  • 添加class=”bg”属性并去除其他元素已添加过的class=”bg”属性

1
$(this).parent().nextAll('div').eq($index).addClass('bg').siblings('div').removeClass('bg');
  • [ ] 封装调用
    1
    2
    3
    $.each($('.box'), function() {
    tab($(this));
    })

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function tab($box) {
var $lis = $box.find('li'); //获取所有li标签
$lis.on('click', function() {
var $index = $(this).index(); //当前元素索引
//end()回到最原始的那个对象
$(this).addClass('bg').siblings().removeClass('bg').end();
$(this).parent().nextAll('div').eq($index).addClass('bg').siblings('div').removeClass('bg');
$(this).parent().nextAll().each(function(index, item) {
index === $index? $(item).addClass('bg') : $(item).removeClass('bg');
})
});
}
// $('.box').each(function() {
// // console.log($(this));
// tab($(this));
// })
$.each($('.box'), function() {
//有多少个.box执行多少次 $(this)其实就是每一个.box
tab($(this));
})